package com.saoft.fangcms.web.controller.cms;

import com.saoft.fangcms.generator.preview.FreemarkerStringComponent;
import com.saoft.fangcms.modules.cms.entity.TemplateData;
import com.saoft.fangcms.modules.cms.service.TemplateDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PreviewAndStaticController {

    @Autowired
    FreemarkerStringComponent stringComponent;

    @Autowired
    TemplateDataService templateDataService;

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * @param theme 主题
     * @param viewFile 渲染的文件
     * @return
     */
    @GetMapping("preview")
    public void preview(
            HttpServletResponse response,
            @RequestParam(value = "theme",defaultValue = "default") String theme,
            @RequestParam(value = "viewFile",defaultValue = "index") String viewFile) throws IOException {

        String templateFile = "/theme/" + theme + "/" + viewFile;
        //data
        List<TemplateData> list = templateDataService.list();
        Map<String, Object> dataMap = new HashMap<>();

        for (TemplateData templateData : list) {
            String sqlCode = templateData.getSqlCode();
            String code = templateData.getCode();
            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sqlCode);
            dataMap.put(code, maps);
        }
        //结果
        String str = stringComponent.generatorString(dataMap, templateFile);
        response.getWriter().append(str);
        System.out.println(str);
    }

}
